﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Form
{
    public partial class ICM_Purchase_Order : System.Web.UI.Page
    {
        IBLLTree bllTree = new TreeBLL();
        IBLLSysYearType bllYearType = new SysYearTypeBLL();
        IBLLMasterPurchaseType bllPurchaseType = new MasterPurchaseTypeBLL();
        IBLLSysRecordStatus bllStatus = new SysRecordStatusBLL();
        IBLLSysProgress bllProgress = new SysProgressBLL();
        IBLLPrePurchaseRequest bllPPR = new PrePurchaseRequestBLL();
        IBLLMasterPurchaseMethod bllMasPurchaseMethod = new MasterPurchaseMethodBLL();
        PurchaseRequestBLL bllPurchaseRequest = new PurchaseRequestBLL();
        IBLLHrmEmployee bllEmployee = new HrmEmployeeBLL();
        SysControlBLL bllSysCon = new SysControlBLL();
        PurchaseOrderBLL bllPcOrder = new PurchaseOrderBLL();
        BidderBLL bllBidder = new BidderBLL();
        int ItemsPerRequest = 10;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDefault();
                LoadYearType();
                LoadPurchaseType();
                LoadRecordStatus();
                LoadPurchaseMethod();
                LoadOperationName();
                LoadPurchaseOrder();
            }
        }

        protected void LoadDefault()
        {
            SysControlInfo infoDefault = bllSysCon.GetDefaultData();
            if (infoDefault.YearType != null)
            {
                cbYearType.SelectedValue = infoDefault.YearType.ToString();
                Session["YearType"] = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            }
            if (infoDefault.Year != null)
            {
                txtYear.Text = infoDefault.Year.ToString();
                Session["Year"] = Convert.ToInt32(txtYear.Text);
            }
        }

        protected void LoadYearType()
        {
            IList<SysYearTypeInfo> infoList = bllYearType.GetSysYearType();
            cbYearType.DataSource = infoList;
            cbYearType.DataBind();
        }

        protected void LoadPurchaseMethod()
        {
            IList<MasterPurchaseMethodInfo> infoList = bllMasPurchaseMethod.GetNameListMasterPurchaseMethod();
            cbPurchaseMethod.DataSource = infoList;
            cbPurchaseMethod.DataBind();
        }

        protected void LoadPurchaseType()
        {
            IList<MasterPurchaseTypeInfo> infoList = bllPurchaseType.GetMasterPurchaseType();
            cbPurchaseType.DataSource = infoList;
            cbPurchaseType.DataBind();
        }

        protected void LoadOperationName()
        {
            IList<HrmEmployeeInfo> infoEmp = bllPPR.GetPrePurchaseRequestOperationName(1);
            cbOperationName.DataSource = infoEmp;
            cbOperationName.DataBind();
        }

        protected void LoadRecordStatus()
        {
            IList<SysRecordStatusInfo> infoList = bllStatus.GetSysRecordStatusTransaction();
            cbStatus.DataSource = infoList;
            cbStatus.DataBind();
        }

        protected void RadManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
        {
            if (e.Argument == "CloseWindow")
            {
                LoadPurchaseOrder();
            }
            else if (e.Argument == "Rebind")
            {
                LoadPurchaseOrder();
            }
            else
            {
                LoadPurchaseOrderInstallment();
            }
        }

        protected void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            if (RadTabStrip1.SelectedTab.Value == "One")
            {
                LoadPurchaseOrder();
            }
            else
            {
                LoadPurchaseOrderInstallment();
            }
        }

        protected void OnAjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            RadAjaxPanel1.Controls.Add(Page.LoadControl("../UserControl/Personal_Data.ascx"));
        }

        protected void btnShow_Click(object sender, EventArgs e)
        {
            Session["YearType"] = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            Session["Year"] = Convert.ToInt32(txtYear.Text);

            if (RadTabStrip1.SelectedTab.Value == "Normal")
            {
                LoadPurchaseOrder();
            }
            else
            {
                LoadPurchaseOrderInstallment();
            }
        }

        // tab กรณีส่งมอบงวดเดียว 

        protected void LoadPurchaseOrder()
        {
            Nullable<int> YearTypeSeq = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            Nullable<int> Year = (txtYear.Text.Trim() == "") ? null : (Nullable<int>)Convert.ToInt32(txtYear.Text.Trim());
            Nullable<int> PurchaseMethodSeq = (cbPurchaseMethod.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbPurchaseMethod.SelectedValue.ToString()) : null;
            Nullable<int> PurchaseTypeSeq = (cbPurchaseType.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbPurchaseType.SelectedValue.ToString()) : null;
            Nullable<int> OperationNameSeq = null;//Convert.ToInt32(cbPurchaseMethod.SelectedValue.ToString());
            Nullable<int> Status = (cbStatus.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbStatus.SelectedValue.ToString()) : null;

            IList<PurchaseOrderInfo> infoList = bllPcOrder.GetPurchaseOrder(YearTypeSeq, Year, PurchaseMethodSeq, PurchaseTypeSeq, OperationNameSeq, Status);
            Grid.DataSource = infoList;
            Grid.DataBind();
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            IList<PurchaseOrderInfo> infoList = new List<PurchaseOrderInfo>();
            foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
            {
                PurchaseOrderInfo info = new PurchaseOrderInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPcOrder.DeleteAll(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadPurchaseOrder();
        }

        protected void Grid_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            LoadPurchaseOrder();
        }

        protected void cbSeller_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<BidderInfo> infoList = bllBidder.GetSellerPurchaseOrder(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbSeller.Items.Add(new RadComboBoxItem(infoList[i].InfoMasContact.Name_th, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdPurchaseMethodName = new TableCell();
                Label lblPurchaseMethodName = new Label();
                lblPurchaseMethodName.Text = infoList[i].InfoPurchaseRequest.InfoPurchaseMethod.Name + infoList[i].InfoPurchaseRequest.InfoPurchaseType.Name;
                tdPurchaseMethodName.Width = Unit.Pixel(100);
                tdPurchaseMethodName.Controls.Add(lblPurchaseMethodName);
                tr.Cells.Add(tdPurchaseMethodName);

                TableCell tdContactGroup = new TableCell();
                Label lblContactGroup = new Label();
                lblContactGroup.Text = infoList[i].InfoMasContact.InfoGroup.Name;
                tdContactGroup.Width = Unit.Pixel(100);
                tdContactGroup.Controls.Add(lblContactGroup);
                tr.Cells.Add(tdContactGroup);

                TableCell tdContactName = new TableCell();
                Label lblContactName = new Label();
                lblContactName.Text = infoList[i].InfoMasContact.Name_th;
                tdContactName.Width = Unit.Pixel(150);
                tdContactName.Controls.Add(lblContactName);
                tr.Cells.Add(tdContactName);

                TableCell tdBidRefNo = new TableCell();
                Label lblBidRefNo = new Label();
                lblBidRefNo.Text = infoList[i].InfoBid.Ref_no;
                tdBidRefNo.Width = Unit.Pixel(100);
                tdBidRefNo.Controls.Add(lblBidRefNo);
                tr.Cells.Add(tdBidRefNo);

                TableCell tdBidName = new TableCell();
                Label lblBidName = new Label();
                lblBidName.Text = infoList[i].InfoBid.Name;
                tdBidName.Width = Unit.Pixel(150);
                tdBidName.Controls.Add(lblBidName);
                tr.Cells.Add(tdBidName);

                TableCell tdNetAmount = new TableCell();
                Label lblNetAmount = new Label();
                lblNetAmount.Text = ((double)infoList[i].NetAmount).ToString("#,##0.00"); ;
                tdNetAmount.Width = Unit.Pixel(100);
                tdNetAmount.Controls.Add(lblNetAmount);
                tr.Cells.Add(tdNetAmount);

                ((Table)cbSeller.Items[j].FindControl("tableSeller")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        protected void clearFilter_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid.MasterTableView.FilterExpression = string.Empty;
            LoadPurchaseOrder();
        }

        // tab กรณีส่งมอบหลายงวด

        protected void LoadPurchaseOrderInstallment()
        {
            Nullable<int> YearTypeSeq = Convert.ToInt32(cbYearType.SelectedValue.ToString());
            Nullable<int> Year = (txtYear.Text.Trim() == "") ? null : (Nullable<int>)Convert.ToInt32(txtYear.Text.Trim());
            Nullable<int> PurchaseMethodSeq = (cbPurchaseMethod.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbPurchaseMethod.SelectedValue.ToString()) : null;
            Nullable<int> PurchaseTypeSeq = (cbPurchaseType.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbPurchaseType.SelectedValue.ToString()) : null;
            Nullable<int> OperationNameSeq = null;//Convert.ToInt32(cbPurchaseMethod.SelectedValue.ToString());
            Nullable<int> Status = (cbStatus.SelectedIndex >= 0) ? (Nullable<int>)Convert.ToInt32(cbStatus.SelectedValue.ToString()) : null;

            IList<PurchaseOrderInfo> infoList = bllPcOrder.GetPurchaseOrderInstallment(YearTypeSeq, Year, PurchaseMethodSeq, PurchaseTypeSeq, OperationNameSeq, Status);
            Grid_Many.DataSource = infoList;
            Grid_Many.DataBind();
        }

        protected void Delete_Many_Click(object sender, EventArgs e)
        {
            IList<PurchaseOrderInfo> infoList = new List<PurchaseOrderInfo>();
            foreach (GridDataItem data in Grid_Many.MasterTableView.GetSelectedItems())
            {
                PurchaseOrderInfo info = new PurchaseOrderInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPcOrder.DeleteAll(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadPurchaseOrderInstallment();
        }

        protected void Grid_Many_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            LoadPurchaseOrderInstallment();
        }

        protected void cbSellerMany_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<BidderInfo> infoList = bllBidder.GetSellerPurchaseOrder(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbSellerMany.Items.Add(new RadComboBoxItem(infoList[i].InfoMasContact.Name_th, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdPurchaseMethodName = new TableCell();
                Label lblPurchaseMethodName = new Label();
                lblPurchaseMethodName.Text = infoList[i].InfoPurchaseRequest.InfoPurchaseMethod.Name + infoList[i].InfoPurchaseRequest.InfoPurchaseType.Name;
                tdPurchaseMethodName.Width = Unit.Pixel(100);
                tdPurchaseMethodName.Controls.Add(lblPurchaseMethodName);
                tr.Cells.Add(tdPurchaseMethodName);

                TableCell tdContactGroup = new TableCell();
                Label lblContactGroup = new Label();
                lblContactGroup.Text = infoList[i].InfoMasContact.InfoGroup.Name;
                tdContactGroup.Width = Unit.Pixel(100);
                tdContactGroup.Controls.Add(lblContactGroup);
                tr.Cells.Add(tdContactGroup);

                TableCell tdContactName = new TableCell();
                Label lblContactName = new Label();
                lblContactName.Text = infoList[i].InfoMasContact.Name_th;
                tdContactName.Width = Unit.Pixel(150);
                tdContactName.Controls.Add(lblContactName);
                tr.Cells.Add(tdContactName);

                TableCell tdBidRefNo = new TableCell();
                Label lblBidRefNo = new Label();
                lblBidRefNo.Text = infoList[i].InfoBid.Ref_no;
                tdBidRefNo.Width = Unit.Pixel(100);
                tdBidRefNo.Controls.Add(lblBidRefNo);
                tr.Cells.Add(tdBidRefNo);

                TableCell tdBidName = new TableCell();
                Label lblBidName = new Label();
                lblBidName.Text = infoList[i].InfoBid.Name;
                tdBidName.Width = Unit.Pixel(150);
                tdBidName.Controls.Add(lblBidName);
                tr.Cells.Add(tdBidName);

                TableCell tdNetAmount = new TableCell();
                Label lblNetAmount = new Label();
                lblNetAmount.Text = ((double)infoList[i].NetAmount).ToString("#,##0.00"); ;
                tdNetAmount.Width = Unit.Pixel(100);
                tdNetAmount.Controls.Add(lblNetAmount);
                tr.Cells.Add(tdNetAmount);

                ((Table)cbSellerMany.Items[j].FindControl("tableSellerMany")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        protected static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void clearFilter_Many_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid_Many.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid_Many.MasterTableView.FilterExpression = string.Empty;
            LoadPurchaseOrderInstallment();
        }
    }
}
